/**
 * 自定义ueditor指令
 */
define(function (require, exports, module) {
    var angular = require('angular');

    var module = angular.module('ueditor',[]);

    //加载config
    require.async('/static_public/js/lib/ueditor/ueditor.config');
    module.directive('ueditor',['$timeout',
        function ($timeout) {
            return{
                restrict: 'EA',
                require: 'ngModel',
                scope: {
                    height: '@?'
                },
                link: function (scope, element, attr, ctrl) {
                    var _self = this,
                        _initContent='',
                        editor,
                        editorReady = false;

                    var fexUE = {
                        initEditor: function () {
                            var _self = this;

                            editor = new UE.ui.Editor({
                                initialContent: _initContent,
                                toolbars:window.UEDITOR_CONFIG.toolbarStyles["text"],
                                initialFrameHeight:scope.height || 120,
                                autoHeightEnabled:false,
                                wordCount:false,
                                elementPathEnabled: false
                            });

                            editor.render(element[0]);
                            editor.ready(function () {
                                editorReady = true;
                                _self.setContent(_initContent);

                                editor.addListener('contentChange', function () {
                                    scope.$apply(function () {
                                        ctrl.$setViewValue(editor.getContent());
                                    });
                                });
                            });
                        },
                        setContent: function (content) {
                            if (editor && editorReady) {
                                editor.setContent(content);
                            }
                        }
                    };

                    /**
                     * 当Model改变值得时候赋值。
                     */
                    ctrl.$render = function () {
                        _initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
                        fexUE.setContent(_initContent);
                    };
                    seajs.use(['/static_public/js/lib/ueditor/ueditor.all'],function(){
                        fexUE.initEditor();
                    });
                }
            }
        }]
    )

});